import React from 'react';
import type { TabsProps } from 'antd';
import { ConfigProvider } from 'antd';
import { useModel } from 'umi';
import type { AudPageMenuItem, AudTab } from '../types';
import { Menu, Tabs, Dropdown } from 'antd';
import getIcon from '@/utils/icon';
import { isRunInFrame } from '@/utils/env';

type AudTabsProps = {
  tabs: AudTab[];
  activeTabKey: string;
  // 弹出菜单
  popMenu: {
    items: {
      key: AudPageMenuItem;
      title: string;
      icon?: React.ReactNode;
    }[];
    onClick: any;
  };
} & Omit<TabsProps, 'activeKey'>;

const setTab = (tab: React.ReactNode, key: string, icon: React.ReactNode, menu: any) => (
  <span onContextMenu={(event) => event.preventDefault()}>
    <Dropdown overlay={menu} trigger={['contextMenu']}>
      <span>
        {icon}
        {tab}
      </span>
    </Dropdown>
  </span>
);

const AudTabs: React.FC<AudTabsProps> = (props) => {
  const { tabs, activeTabKey, popMenu, ...restProps } = props;
  const { initialState } = useModel('@@initialState');
  /** 移除一个页 并计算出显示的页 */
  const menu = () => {
    return (
      <Menu
        onClick={({ key }) => {
          popMenu.onClick(key);
        }}
      >
        {popMenu.items.map((item) => (
          <Menu.Item key={item.key} icon={item.icon}>
            {item.title}
          </Menu.Item>
        ))}
      </Menu>
    );
  };

  return (
    <ConfigProvider componentSize={initialState?.settings?.componentSize || 'small'}>
      <Tabs
        className="page-tabs"
        // renderTabBar={() => undefined}
        tabBarStyle={{ display: isRunInFrame ? 'none' : '' }}
        type="editable-card"
        size="small"
        hideAdd
        activeKey={activeTabKey}
        tabBarExtraContent={{
          right: (
            <Dropdown overlay={menu}>
              <a onClick={(e) => e.preventDefault()}>{getIcon('UnorderedList')}</a>
            </Dropdown>
          ),
        }}
        {...restProps}
      >
        {tabs.map((pane) => (
          <Tabs.TabPane
            tab={setTab(pane.title, pane.key, pane.icon, menu)}
            key={pane.key}
            closable={pane.closable}
          >
            {<pane.content state={pane.state} />}
          </Tabs.TabPane>
        ))}
      </Tabs>
    </ConfigProvider>
  );
};

export default AudTabs;
